package com.mongoosehome.web.util;

import com.mongoosehome.web.enumcommon.PageSizeEnum;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;

/**
 * Request辅助函数的定义
 *
 */
public class RequestUtils {

    /**
     * 从Request中获得指定参数名称的值
     *
     * @param request
     * @param parameter
     * @param defaultValue
     * @return
     */
    public static String getStringParameter(HttpServletRequest request, String parameter, String defaultValue) {
        return getStringParameter(request, parameter, defaultValue, false);
    }

    /**
     * 从Request中获得指定参数名称的值
     *
     * @param request
     * @param parameter
     * @param defaultValue
     * @param encodingToCN
     * @return
     */
    public static String getStringParameter(HttpServletRequest request, String parameter,
            String defaultValue, boolean encodingToCN) {
        String value = request.getParameter(parameter);
        if (null == value) {
            return defaultValue;
        }
        if (encodingToCN) {
            return StringUtils.encodingToCN(value.trim());
        } else {
            return value.trim();
        }
    }

    /**
     * 重设Request中的参数
     *
     * @param request
     * @param parameterName
     * @param defaultValue
     * @param encodingToCN
     * @return
     */
    public static void resetParameter(HttpServletRequest request, String parameterName) {
        String value = request.getParameter(parameterName);
        if (null == value) {
            return;
        } else {
            request.setAttribute(parameterName, value);
        }
    }

    /**
     * 重设Request中的参数
     *
     * @param request
     * @param parameterName
     * @param defaultValue
     * @param encodingToCN
     */
    public static void resetParameter(HttpServletRequest request,
            String parameterName, String defaultValue, boolean encodingToCN) {
        String value = getStringParameter(request, parameterName, defaultValue, encodingToCN);
        if (null == value) {
            return;
        } else {
            request.setAttribute(parameterName, value);
        }
    }

    /**
     * 从Request中获得指定参数名称的值,并按指定的分隔符分隔为数组返回
     *
     * @param request
     * @param parameterName 参数名
     * @param defaultValue 默认值(当请求中不存在指定名称的参数时的返回值)
     * @param splitSymbol 分隔符
     * @return
     */
    public static String[] getStringArrayParameter(HttpServletRequest request,
            String parameterName, String splitSymbol, String[] defaultValue) {
        return getStringArrayParameter(request, parameterName, splitSymbol, defaultValue, false);
    }

    /**
     * 从Request中获得指定参数名称的值,并按指定的分隔符分隔为数组返回
     *
     * @param request
     * @param parameterName 参数名
     * @param splitSymbol 分隔符
     * @param encodingToCN 是否需要将参数的值执行默认的中文编码转换
     * @return
     */
    public static String[] getStringArrayParameter(HttpServletRequest request,
            String parameterName, String splitSymbol, String[] defaultValue, boolean encodingToCN) {
        String value = request.getParameter(parameterName);
        if (null == value || value.length() == 0) {
            return defaultValue;
        }
        if (encodingToCN) {
            value = StringUtils.encodingToCN(value);
        }

        String[] values = value.split(splitSymbol);
        if (values == null || values.length == 0) {
            return defaultValue;
        } else {
            return values;
        }
    }

    /**
     * 将指定的字符串转换成GB2312的编码
     *
     * @param isoString
     * @return
     */
    public static String encodingToCN(String isoString) {
        if (null == isoString || isoString.length() < 1) {
            return "";
        }
        try {
            String returnString = new String(isoString.getBytes("ISO-8859-1"), "GB2312");
            return returnString;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 从Request中获得指定参数名称的值
     *
     * @param request
     * @param parameter
     * @param defaultValue
     * @return
     */
    public static long getLongParameter(HttpServletRequest request, String parameter,
            long defaultValue) {
        String value = request.getParameter(parameter);
        if (null == value || value.length() == 0) {
            return defaultValue;
        }
        return Long.parseLong(value);
    }

    /**
     * 从Request中获得指定参数名称的值
     *
     * @param request
     * @param parameter
     * @param defaultValue
     * @return
     */
    public static int getIntParameter(HttpServletRequest request, String parameter,
            int defaultValue) {
        String value = request.getParameter(parameter);
        if (null == value || value.length() == 0) {
            return defaultValue;
        }
        return Integer.parseInt(value.trim());
    }

    /**
     * 从Request中获得指定参数名称的值
     *
     * @param request
     * @param parameter
     * @param defaultValue
     * @return
     */
    public static boolean getBooleanParameter(HttpServletRequest request, String parameter,
            boolean defaultValue) {
        String value = request.getParameter(parameter);
        if (null == value || value.length() == 0) {
            return defaultValue;
        } else if (value.equalsIgnoreCase("true") || value.equalsIgnoreCase("Y")
                || value.equalsIgnoreCase("1")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 设置需要用户确认的提示信息
     *
     * @param request
     * @param confirmMsg 需要用户确认的提示信息
     */
    public static void setConfirmMsg(HttpServletRequest request, String confirmMsg) {
        request.setAttribute("confirmMsg", confirmMsg);
    }

    /**
     * 设置不需要用户确认的提示信息
     *
     * @param request
     * @param commonMsg 不需要用户确认的提示信息
     */
    public static void setCommonMsg(HttpServletRequest request, String commonMsg) {
        request.setAttribute("message", commonMsg);
    }

    /**
     * 获取分页中每一页的条数
     *
     * @param request
     * @return
     */
    public static int getPageMaxResult(HttpServletRequest request) {
        return RequestUtils.getIntParameter(request, "limit", PageSizeEnum.PAGE_SIZE.getValue());
    }

    /**
     * 获取分页的开始索引号
     *
     * @param request
     * @return
     */
    public static int getPageFirstNo(HttpServletRequest request) {
        return RequestUtils.getIntParameter(request, "start", 1);
    }

    /**
     * 获取排序的字段名称
     *
     * @param request
     * @return
     */
    public static String getPageSortField(HttpServletRequest request) {
        String sortField = RequestUtils.getStringParameter(request, "sort", "");
        return sortField.replaceAll("_", ".");
    }

    /**
     * 获取页面排序方式
     *
     * @param request
     * @return
     */
    public static String getPageSortDir(HttpServletRequest request) {
        return RequestUtils.getStringParameter(request, "dir", "asc");
    }

    /**
     * 获取请求对应的根路径，该路径兼容使用虚拟路径和网站方式的部署
     *
     * @param request
     * @return 请求对应的根路径，
     * 如果使用虚拟路径方式部署(http:\\[hostname]:[port]\myApp)，返回类似“/myApp/”的字符串；
     * 如果使用网站方式部署(http:\\[hostname]:[port])，返回字符串"/"。
     */
    public static String getRootPath(HttpServletRequest request) {
        if (request == null) {
            return "/";
        }

        String path = request.getContextPath();
        return (path.endsWith("/") ? path : path + "/");
    }

    /**
     * 获取请求路径
     *
     * @param request
     * @return
     */
    public static String getRequestPath(HttpServletRequest request) {
        String yoururl = request.getRequestURL().toString();
        String queryString = request.getQueryString().toString();
        StringBuilder sb = new StringBuilder();
        sb.append(yoururl).append("?").append(queryString);
        return sb.toString();
    }

    /**
     * 取得当前IP
     *
     * @param request
     * @return
     */
    public static String getIP(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static boolean isPost(HttpServletRequest request) {
        if (request.getMethod().indexOf("P") > -1) {
            return true;
        }
        return false;
    }

    /**
     * 下载一个网页内容
     *
     * @param urlStr
     * @return
     * @throws IOException
     */
    public static byte[] downloadHtmlforStream(String urlStr) throws IOException {
        byte responseBody[] = null;
        try {
            URL url = new URL(urlStr);
            URLConnection cnn = url.openConnection();

            ByteArrayOutputStream outstream = new ByteArrayOutputStream();
            InputStream instream = cnn.getInputStream();
            byte buffer[] = new byte[4096];
            int i=instream.read(buffer);
            while (i > 0) {
                outstream.write(buffer, 0, i);
                i=instream.read(buffer);
            }
            outstream.close();
            responseBody = outstream.toByteArray();
        } catch (FileNotFoundException e) {
            System.out.println("XML File Not Found!");
        } catch (IOException e) {
            System.out.println("File Not Found!");
        }

        return responseBody;
    }
}
